package com.xusheng.cli.controller.user;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.entity.commentModule.Comment;
import com.xusheng.cli.entity.frontUserModule.FrontUser;
import com.xusheng.cli.entity.videoModule.CommentVO;
import com.xusheng.cli.entity.videoModule.ShortVideoVO;
import com.xusheng.cli.entity.videoModule.Video;
import com.xusheng.cli.service.CommentService;
import com.xusheng.cli.service.FrontUserService;
import com.xusheng.cli.service.VideoService;
import com.xusheng.cli.service.WatchingRecordService;
import com.xusheng.cli.tools.CurrentPlayerUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 视频播放接口
 *
 * @author lyh
 * @since 2023-04-27 14:09
 */
@RestController
@Slf4j
@RequestMapping("/user/v1/video")
public class VideoController {

    @Resource
    private VideoService videoService;
    @Resource
    private WatchingRecordService watchingRecordService;
    @Resource
    private FrontUserService frontUserService;
    @Resource
    private CommentService commentService;

    /**
     * 播放视频
     *
     * @param id 视频编号
     * @return 返回结果
     */
    @GetMapping("/play/{id}")
    public Result<Map<String, Object>> play(@PathVariable long id) {
        Map<String, Object> data = videoService.playVideo(id);
        return Result.success(data);
    }

    /**
     * 观看记录接口
     *
     * @param current 第几页
     * @param size    每页记录数
     * @param type    1-近一周 2-近一个月 3-更早
     * @return 返回结果
     */
    @GetMapping("/watchingRecord")
    public Result<MyPage<Video>> watchingRecordList(long current, long size, Integer type) {
        long userId = CurrentPlayerUserUtil.getUserId();
        MyPage<Video> page = watchingRecordService.watchingRecordList(userId, current, size, type);
        return Result.success(page);
    }

    @GetMapping("/list/short/new/{current}")
    public Result<List<ShortVideoVO>> newShortVideoList(@PathVariable int current) {
        Long userId = CurrentPlayerUserUtil.getUserId();
        FrontUser currentUser = frontUserService.getById(userId);
        Boolean vip = false;
        // 当前用户是否为vip
        if (currentUser.getVipExpires() != null && currentUser.getVipExpires().isAfter(LocalDateTime.now()) && currentUser.getVipId() != null) {
            vip = true;
        }
        List<ShortVideoVO> shortVideoVOS = videoService.getShortVideoList(userId, vip, current * 10);
        if (shortVideoVOS.size() == 0) {
            shortVideoVOS = videoService.getShortVideoList(userId, vip, 0);
        }
        log.info("视频数据为{}", shortVideoVOS);
        shortVideoVOS.forEach(v -> {
            v.set_id(v.getId());
            v.setLike_n(v.getLikeN());
            v.setSms_n(v.getSmsN());
            // 获取评论
            List<Comment> comments = commentService.list(new LambdaQueryWrapper<>(new Comment()).eq(Comment::getVideoId, v.get_id()));
            List<CommentVO> commentList = new ArrayList<>();
            for (Comment comment : comments) {
                CommentVO commentVO = new CommentVO();
                commentVO.setUserID(comment.getUserId().toString());
                FrontUser user = frontUserService.getById(comment.getUserId());
                commentVO.setUsername(DesensitizedUtil.mobilePhone(user.getAccount()));
                commentVO.setPinlunContent(comment.getComment());
                commentVO.setTime(comment.getCreateTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
                commentList.add(commentVO);
            }
            v.setPinlun(commentList);
        });
        return Result.success(shortVideoVOS);
    }

    @PostMapping("/short/count")
    public Result<FrontUser> shortCount() {
        Long userId = CurrentPlayerUserUtil.getUserId();
        FrontUser user = frontUserService.getById(userId);
        if (user.getVipExpires() == null || user.getVipExpires().isBefore(LocalDateTime.now())) {
            if (user.getWatchCountShort() > 0) {
                user.setWatchCountShort(user.getWatchCountShort() - 1);
                frontUserService.updateById(user);
            }
        }
        return Result.success(user);
    }
}
